package com.rfid.emergencywarehouse.reader;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.handheld.uhfr.UHFRManager;
import com.rfid.base.util.LogUtils;
import com.rfid.emergencywarehouse.entity.TagInfo;
import com.uhf.api.cls.Reader;

import java.util.List;

import cn.pda.serialport.Tools;

public class BX6100UhfImpl implements IRfidImpl{

    boolean isReading;
    RfidListener mRfidListener;

    @Override
    public void setRfidListener(RfidListener listener) {
        mRfidListener = listener;
    }

    @Override
    public void connect(Context context) {
        UHFRManager.getInstance();
    }

    @Override
    public boolean setPower(int power) {
        Reader.READER_ERR err = UHFRManager.getInstance().setPower(power,power);
        if(err== Reader.READER_ERR.MT_OK_ERR){
            return true;
        }
        LogUtils.v("setPower fail err = " + err);
        return false;
    }

    @Override
    public int getPower() {
        int power[] = UHFRManager.getInstance().getPower();
        if (power != null) {
            return power[0];
        }
        return 0;
    }

    @Override
    public void startScan() {
        if (isReading) {
            return;
        }
        isReading = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isReading) {
                    try {
                        List<Reader.TAGINFO> listTag = UHFRManager.getInstance().tagInventoryByTimer((short) 50);
                        if (listTag != null && !listTag.isEmpty()) {
                            LogUtils.e("inventory listTag size = " + listTag.size());
                            for (Reader.TAGINFO taginfo : listTag) {
                                TagInfo info = pooled6cData(taginfo);
                                if (mRfidListener != null) {
                                    mRfidListener.onRfid(info.getEpc());
                                }
                            }
                        }
                    } catch (Exception e) {
                        LogUtils.e(e);
                    }
                }
            }
        }).start();
    }

    public TagInfo pooled6cData(Reader.TAGINFO info) {
        String epcAndTid = Tools.Bytes2HexString(info.EpcId, info.EpcId.length);
        Log.i("Inv", "[pooled6cData] tag epc: " + epcAndTid);
        TagInfo tag = new TagInfo();
        tag.setType("6C");
        tag.setEpc(Tools.Bytes2HexString(info.EpcId, info.EpcId.length));
        tag.setCount(1l);
        if (info.EmbededData != null && info.EmbededDatalen > 0) {
            tag.setTid(Tools.Bytes2HexString(info.EmbededData, info.EmbededDatalen));
        }
        tag.setRssi(info.RSSI + "");
        return tag;
    }

    @Override
    public void stop() {
        isReading = false;
    }

    @Override
    public void quit() {
        UHFRManager.getInstance().close();
    }

}
